<!-- eslint-disable import/no-unresolved -->
<template>
  <div class="page-main">
    <query-page
      ref="queryPageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      title="采购订单变更管理"
      :total="total"
      @query-data="getData"
    >
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['pms:order-change-main:save']"
            type="primary"
            @click="newlyIncreased"
            >新增</a-button
          >
        </a-space>
      </template>
      <template #contentUrl="{ record }">
        <div>
          <a-button
            v-permission="['pms:order-change-main:createContent']"
            type="text"
            @click="generate(record)"
          >
            生成正文</a-button
          >
          <a-button
            v-permission="['pms:order-change-main:openFileUrl']"
            type="outline"
            status="success"
            :disabled="!record.contentUrl"
            @click="examine(record)"
            >查看</a-button
          >
        </div>
      </template>
      <template #operate="{ record }">
        <a-button
          v-permission="['pms:order-change-detail:page']"
          type="text"
          @click="rowClick(record)"
          >详情</a-button
        >

        <a-button
          v-permission="['pms:order-change-main:update']"
          :hidden="record.status !== '0'"
          type="text"
          @click="compile(record)"
          >编辑</a-button
        >
        <a-button
          v-permission="['pms:order-change-main:delete']"
          type="text"
          status="danger"
          :hidden="record.status !== '0'"
          @click.stop="handleDelete(record)"
          >删除</a-button
        >
        <a-button
          v-permission="['pms:order-change-main:submitApproval']"
          :hidden="record.status !== '0'"
          type="text"
          @click.stop="handleApprove(record)"
          >提交审批</a-button
        >
      </template>
    </query-page>
    <Detail
      v-if="detailShow"
      ref="detailRef"
      v-model:detail-show="detailShow"
    />
    <!-- 添加按钮 -->
    <purchaseOrderAlterationAdministrationAddPage
      v-if="contentShow"
      ref="contentRef"
      v-model:content-show="contentShow"
      @modelCancel="modelCancel"
    />
    <!-- 提价审批 -->
    <!-- <purchaseOrderAlterationAdministrationSubmitExamine
      v-if="contentShow"
    ></purchaseOrderAlterationAdministrationSubmitExamine> -->
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, ref } from 'vue';

  import queryPage from '@/common/components/query-page/index.vue';
  import {
    formRenderConfig,
    formComponentConfig,
  } from '@/views/purchase-order/components/formComp/baseFormConfigAlterationAdministration';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '@/views/purchase-order/components/tableComp/baseTableConfigAlterationAdministration';
  import purchaseOrderAlterationAdministrationAddPage from '@/views/purchase-order/purchase-order-alterationAdministrationAddPage/index.vue';
  // import purchaseOrderAlterationAdministrationSubmitExamine from '@/views/purchase-order/purchase-order-alterationAdministrationSubmitExamine/index.vue';
  import {
    getPage,
    deleteOrder,
    submitApproval,
    createContent,
  } from '@/api/purchase-order/orderApi';
  import { Message } from '@arco-design/web-vue';
  import modalPromise, { info } from '@/common/utils/modal-promise';
  import { hasDataAndBack } from '@/common/utils/index';
  import ntko from '@/common/service/ntko/index';

  import Detail from './detail.vue';

  import { baseRenderKeys } from './baseRenderData';

  const queryPageRef = ref();
  const selectedKeys = ref([]);
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  const detailShow = ref(false);
  const contentShow = ref(false);
  const detailRef = ref();
  const contentRef = ref();
  const total = ref(0);

  // 渲染检索项
  const formRenderKeys = ref<any[]>([
    ...baseRenderKeys.finishedProduct.formRenderKeys,
  ]);

  //  上面的表格 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([
    ...baseRenderKeys.finishedProduct.upTableRenderKeys,
  ]);
  // 添加弹框的事件
  const newlyIncreased = () => {
    contentShow.value = true;
    nextTick(() => {
      contentRef.value.conTitle = '新增';
    });
  };
  // 编辑弹框
  const compile = (val) => {
    contentShow.value = true;
    nextTick(() => {
      contentRef.value.conTitle = '编辑';
      contentRef.value.init(val.id);
    });
  };
  const handleDelete = async (record: any) => {
    try {
      await modalPromise.info({
        title: '提示',
        content: '您确定要删除当前数据？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    await deleteOrder(record.id);
    Message.success({
      content: '删除成功!',
    });
    getData();
  };
  const handleApprove = async (record: any) => {
    try {
      await modalPromise.info({
        title: '提示',
        content: '您确定要提交审批当前数据？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    // isLoading.value = true;
    await submitApproval({ id: record.id });
    // isLoading.value = false;
    Message.success({
      content: '提交成功!',
    });
    getData();
  };
  const modelCancel = () => {
    getData();
  };
  const getData = async (queryInfo: object) => {
    const page = queryPageRef.value.getStatus();
    renderData.value = [];

    isLoading.value = true;
    console.log(queryInfo, 'queryInfoqueryInfo');

    const res = await getPage({ ...queryInfo, ...page });
    try {
      if (res.code === 200) {
        total.value = res.data.total;
        renderData.value = res.data.list;
        refreshNumData(renderData.value, total.value);
      }
    } finally {
      isLoading.value = false;
    }
  };
  // 列表 删除回退的问题
  const refreshNumData = (list: any[], tNum: any) => {
    if (hasDataAndBack(list, tNum, queryPageRef.value?.getStatus().pageNo)) {
      queryPageRef.value?.setCurrent(queryPageRef.value.getStatus().pageNo - 1);
      getData(queryPageRef.value.getStatus());
    }
  };
  const rowClick = (val) => {
    detailShow.value = true;
    nextTick(() => {
      detailRef.value.init(val.id);
      detailRef.value.title = `订单编号${val.id}详情数据`;
    });
  };
  const recordId = ref('');
  const generate = async (record: any) => {
    console.log(record, 'generate');
    recordId.value = record.id;
    const url =
      record.contentUrl ||
      'http://procurement.internal.avicnet.cn:32101/ntko/doc/ntkocreatnew.docx';
    await ntko.createContractDoc(url, {
      secretLevel: record.secretLevel, // 密级
      mId: record.id, // 查询右侧书签的内容
      bizType: '4', // 类型： 1-合同；2-合同变更；3-订单；4-订单变更
      dataId: record.id,
    });
  };

  // 监听文档保存成功了
  ntko.on('save', async (res) => {
    console.log(res, '监听文档保存成功了');

    info({
      title: '页面保存成功',
      content: '内容保存成功',
    });
    if (res.dataId !== recordId.value) {
      return;
    }
    const params = {
      id: recordId.value,
      contentUrl: res.data,
    };
    try {
      const saveRes = (await createContent(params)) as any;
      console.log(saveRes, '页面保存成功');

      if (saveRes.code === 200) {
        getData();
      }
    } finally {
      isLoading.value = false;
    }
  });

  // 监听文档保存成功了
  ntko.on('close', () => {
    info({
      title: '页面关闭了',
      content: '编辑器关闭了',
    });
  });
  const recordContentUrl = ref('');
  const examine = async (record: any) => {
    console.log(record, 'generate');
    recordContentUrl.value = record.contentUrl;
    await ntko.readDoc(recordContentUrl.value);
  };
</script>

<style lang="less" scoped>
  .purchase-order-alteration-inquire-container {
    height: 100%;
    margin: 16px;
    padding: 12px 24px;
    background-color: #fff;
    border-radius: 8px;
  }

  /deep/ .query-page-con {
    padding: 0;
  }
</style>
